<template>
    <div id="drawtoolPanel" v-show="visible" style="background-color: black" class="mev-div-border">
        <el-container>
            <el-header>
                <el-row>
                    <el-col :span="16" style="text-align: left">
                        标注
                    </el-col>
                    <el-col :span="8" style="text-align: right">
                        <i @click="toolbarFunc('close')" size="medium" class="el-icon-close"></i>
                    </el-col>
                </el-row>
            </el-header>
            <el-main class="mev-div-border">
                <el-row>
                    <el-col :span="6">
                        <el-button size="small" style="width: 100%; padding: 8px 0; margin: 0" @click="menuAction('MARKER')"><i class="iconfont iconmarker"></i></el-button>
                    </el-col>
                    <el-col :span="6">
                        <el-button size="small" style="width: 100%; padding: 8px 0; margin: 0" @click="menuAction('POLYLINE')"><i class="iconfont iconpolyline"></i> </el-button>
                    </el-col>
                    <el-col :span="6">
                        <el-button size="small" style="width: 100%; padding: 8px 0; margin: 0" @click="menuAction('POLYGON')"><i class="iconfont iconpolygon"></i> </el-button>
                    </el-col>
                    <el-col :span="6">
                        <el-button size="small" style="width: 100%; padding: 8px 0; margin: 0" @click="RenWuJudge()"><i class="iconfont iconlayer"></i> </el-button>
                    </el-col>
                </el-row>
                <!--                <ul>-->
                <!--                    <li>-->
                <!--                        <i class="iconfont iconmarker icon-class" title="添加标记" :class="{ 'selected-graphic': menuSelected['MARKER'] }" @click="menuAction('MARKER')"></i>-->
                <!--                        <span @click="menuAction('MARKER')" :class="{ 'selected-graphic': menuSelected['MARKER'] }">标记</span>-->
                <!--                    </li>-->
                <!--                    <li>-->
                <!--                        <i class="iconfont iconpolyline icon-class" title="添加线段" :class="{ 'selected-graphic': menuSelected['POLYLINE'] }" @click="menuAction('POLYLINE')"></i>-->
                <!--                        <span @click="menuAction('POLYLINE')" :class="{ 'selected-graphic': menuSelected['POLYLINE'] }">折线</span>-->
                <!--                    </li>-->
                <!--                    <li>-->
                <!--                        <i class="iconfont iconpolygon icon-class" title="添加多边形" :class="{ 'selected-graphic': menuSelected['POLYGON'] }" @click="menuAction('POLYGON')"></i>-->
                <!--                        <span @click="menuAction('POLYGON')" :class="{ 'selected-graphic': menuSelected['POLYGON'] }">多边形</span>-->
                <!--                    </li>-->
                <!--                    &lt;!&ndash;                    <li>&ndash;&gt;-->
                <!--                    &lt;!&ndash;                        <i class="iconfont iconlabel icon-class" title="添加文字" :class="{ 'selected-graphic': menuSelected['LABEL'] }" @click="menuAction('LABEL')"></i>&ndash;&gt;-->
                <!--                    &lt;!&ndash;                        <span @click="menuAction('LABEL')" :class="{ 'selected-graphic': menuSelected['LABEL'] }">文字</span>&ndash;&gt;-->
                <!--                    &lt;!&ndash;                    </li>&ndash;&gt;-->
                <!--                    <li v-if="extendMarkerModel.length">-->
                <!--                        <i class="iconfont iconmodel icon-class" title="添加模型" :class="{ 'selected-graphic': menuSelected['MODEL'] }" @click="menuAction('MODEL')"></i>-->
                <!--                        <span @click="menuAction('MODEL')" :class="{ 'selected-graphic': menuSelected['MODEL'] }">模型</span>-->
                <!--                    </li>-->
                <!-- <li>
            <i
              class="font-btn"
              title="添加文字"
              :class="{'font-selected':menuSelected['LABEL']}"
              @click="menuAction('LABEL')"
            ></i>
            <span @click="menuAction('LABEL')">文字</span>
          </li>-->
                <!--                    <li>-->
                <!--                        <i class="iconfont iconlayer icon-class" :class="{ 'selected-graphic': layerManagerVisible }" title="图层管理" @click="layerManagerVisible = !layerManagerVisible"></i>-->
                <!--                        <span :class="{ 'selected-graphic': layerManagerVisible }" @click="layerManagerVisible = !layerManagerVisible">图层</span>-->
                <!--                    </li>-->
                <!--                </ul>-->
            </el-main>
        </el-container>

        <el-main class="mev-div-border" v-show="editMode">


            <el-row v-show="menuSelected['MARKER']">
                <el-col :span="18">
                    <el-select size="mini" style="padding: 0" v-model="fontSize" allow-create filterable title="字号" default-first-option placeholder="请选择">
                        <el-option v-for="item in fontSizeList" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-color-picker size="mini" v-model="markerColor" id="markerColor" show-alpha></el-color-picker>
                </el-col>
                <el-popover placement="top" width="160" v-model="markerOptionsVisible">
                    <el-input type="textarea" :rows="4" placeholder="请在此定义LabelGraphic" v-model="markerOption"></el-input>

                    <div style="text-align: right; margin: 0">
                        <el-button
                            size="mini"
                            type="text"
                            @click="
                                markerOption = '';
                                markerOptionsVisible = false;
                            "
                        >取消</el-button
                        >
                        <el-button type="primary" size="mini" @click="setLabel">确定</el-button>
                    </div>
                </el-popover>
            </el-row>
            <el-row v-show="menuSelected['POLYLINE']">
                <el-col :span="14">
                    <el-select size="mini" style="padding-left: 0" title="直线类型" class="type-selector" v-model="graphicHeight" default-first-option placeholder="请选择">
                        <el-option v-for="item in heightList" :key="item.value" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="10">
                    <el-select style="margin: 0" size="mini" title="线宽" v-model="lineWidth" allow-create filterable default-first-option placeholder="请选择">
                        <el-option v-for="item in lineWidthList" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-col>
            </el-row>
            <el-row v-show="menuSelected['POLYLINE']" style="margin-top: 5px">
                <el-col :span="12">
                    <el-select size="mini" class="style-selector" title="直线样式" v-model="lineStyle" default-first-option placeholder="请选择">
                        <el-option v-for="item in lineStyleList" :key="item.value" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-color-picker style="width: 100%; margin: 0" size="mini" title="颜色" id="lineColor" v-model="lineColor" show-alpha></el-color-picker>
                </el-col>
                <el-col :span="6">
                    <el-button style="width: 100%; padding-left: 0; padding-right: 0" size="mini" @click="stopCreateOrEdit">结束</el-button>
                </el-col>
            </el-row>
            <el-row v-show="menuSelected['POLYGON']">
                <el-col :span="18">
                    <el-select size="mini" title="多边形类型" class="type-selector" v-model="graphicHeight" default-first-option placeholder="请选择">
                        <el-option v-for="item in heightList" :key="item.value" :label="item.name" :value="item.value"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-color-picker title="填充色" id="polygonColor" v-model="polygonColor" show-alpha size="mini"></el-color-picker>
                </el-col>
            </el-row>
            <el-row v-show="menuSelected['POLYGON']">
                <el-col :span="12">
                    <el-select size="mini" title="边框宽度" v-show="outline" class="width-selector" v-model="outlineWidth" allow-create filterable default-first-option placeholder="请选择">
                        <el-option v-for="item in lineWidthList" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-color-picker title="边框充色" id="outlineColor" v-show="outline" v-model="outlineColor" show-alpha size="mini"></el-color-picker>
                </el-col>

                <el-col :span="6">
                    <el-button style="width: 100%; padding-left: 0; padding-right: 0" size="mini" @click="stopCreateOrEdit">结束</el-button>
                </el-col>
            </el-row>
        </el-main>

        <!--        <el-main class="mev-div-border" v-show="editMode">-->
        <!--            <div class="label-edit-class edit-class" v-show="menuSelected['LABEL']">-->
        <!--                <el-select v-model="fontFamily" class="font-selector" allow-create filterable size="mini" title="字体" default-first-option placeholder="请选择">-->
        <!--                    <el-option v-for="item in fontList" :key="item" :label="item" :value="item"></el-option>-->
        <!--                </el-select>-->
        <!--                <el-select size="mini" v-model="fontSize" class="size-selector" allow-create filterable title="字号" default-first-option placeholder="请选择">-->
        <!--                    <el-option v-for="item in fontSizeList" :key="item" :label="item" :value="item"></el-option>-->
        <!--                </el-select>-->
        <!--                <el-color-picker title="颜色" v-model="markerColor" id="labelColor" show-alpha size="mini"></el-color-picker>-->
        <!--            </div>-->
        <!--            <div class="model-edit-class edit-class" v-show="menuSelected['MODEL']">-->
        <!--                <el-popover placement="bottom" id="model-select" width="160" v-model="modelSelectPanelvisible">-->
        <!--                    <div class="model-select-panel">-->
        <!--                        <img v-for="item in extendMarkerModel" :title="item.name" :key="item.id" @click="selectModel(item)" :src="modelThumb(item)" :onerror="defaultImage" />-->
        <!--                    </div>-->
        <!--                    <i class="iconfont iconmodel model-selector-trigger" slot="reference" title="选择模型"></i>-->
        <!--                </el-popover>-->
        <!--                <el-select v-model="modelMode" size="mini" title="模式" default-first-option placeholder="请选择">-->
        <!--                    <el-option v-for="item in modelModeList" :key="item.value" :label="item.name" :value="item.value"></el-option>-->
        <!--                </el-select>-->
        <!--                <el-color-picker title="颜色" id="modelColor" v-model="modelColor" show-alpha size="mini"></el-color-picker>-->
        <!--                <el-slider v-show="modelMode === 'Mix'" title="混合度" v-model="modelMixed" :min="0" :max="1" :step="0.1" :show-tooltip="true"></el-slider>-->
        <!--            </div>-->
        <!--        </el-main>-->
        <MarkerViewer
            ref="markerManager"
            :attachment="attachment"
            @deleteEvent="deleteMarker"
            @editEvent="editMarker"
            @addEvent="addMarker"
            @updateEvent="updateMarker"
            :extendImage="extendMarkerImage"
        ></MarkerViewer>
        <layerManager
            ref="layerManager"
            @locate="locateGraphic"
            @edit="editGraphic"
            @delete="deleteGraphic"
            @rename="renameGraphic"
            @select="selectGraphic"
            @clear="clearGraphic"
            @close="closeLayerManager"
            @import="importGraphic"
            @export="exportGraphic"
            :tools="tools"
            v-show="layerManagerVisible"
            class="layer-manager-class"
            :class="{ 'edit-layer-manager-class': editMode }"
        ></layerManager>
        <input type="file" v-show="false" @change="importfp" id="graphicuploadhandler" accept=".geojson, .shp" />
    </div>
</template>
<script>
import GraphicManager from "../../../plugins/mev/draw/core/GraphicManager";
import MarkerViewer from "./markerViewer";
import { CesiumPolygon } from "../../../plugins/mev/draw/core/Graphic";
import layerManager from "./layerManager";
import GraphicType from "../../../plugins/mev/draw/core/GraphicType";
import { open } from "shapefile";
import { moveDiv } from "../../../plugins/mev/draw/utils/utils";
import $ from "jquery";
import { checkComponent, checkViewer } from "../../../plugins/mev/draw/utils/utils";
let graphicManager = undefined;
export default {
    name: "cesiumDrawViewer",
    data() {
        return {
            visible: true,
            editMode: false,
            graphicType: undefined,
            menuSelected: {},
            layerManagerVisible: false,
            markerColor: "rgba(255, 255,255, 1)",
            fontSize: "28px",
            markerFont: "sans-serif",
            markerOptionsVisible: false,
            markerOption: "",
            lineColor: "rgba(247,224,32,1)",
            lineWidth: "3px",
            lineWidthList: ["1px", "2px", "3px", "4px", "5px", "6px", "8px", "10px", "12px"],
            lineStyleList: [
                { value: "solid", name: "实线" },
                { value: "dash", name: "虚线" },
                //{ value: "glow", name: "发光线" },
                { value: "arrow", name: "箭头线" }
            ],
            lineStyle: "solid",
            graphicHeight: "NONE",
            //   lineHeight: "GROUND_ADN_MODEL",
            //   polygonHeight: "GROUND_ADN_MODEL",
            heightList: [
                //{ value: "GROUND_ADN_MODEL", name: "依附地形和模型" },

                //{ value: "MODEL", name: "依附模型" },
                { value: "NONE", name: "空间线" },
                { value: "GROUND", name: "依附地形" }
            ],
            outlineWidth: "3px",
            outlineColor: "rgba(247,224,32,1)",
            polygonColor: "rgba(247,224,32,0.5)",
            outline: true,
            imags: [
                "./static/images/markers/1.png",
                "./static/images/markers/2.png",
                "./static/images/markers/3.png",
                "./static/images/markers/4.png",
                "./static/images/markers/5.png",
                "./static/images/markers/6.png",
                "./static/images/markers/7.png",
                "./static/images/markers/8.png"
            ],
            fontSizeList: ["10px", "12px", "14px", "16px", "18px", "20px", "24px", "32px", "64px"],
            fontList: ["sans-serif", "宋体"],
            fontFamily: "sans-serif",
            modelMode: "Highlight",
            modelModeList: [
                { value: "Highlight", name: "高亮" },
                { value: "Replace", name: "替换" },
                { value: "Mix", name: "混合" }
            ],
            modelColor: "#FFFFFF",
            modelMixed: 0.5,
            modelSelectPanelvisible: false,
            selectedModel: undefined,
            taskName: "无任务"
        };
    },
    computed: {
        defaultImage() {
            return 'this.src=""';
        }
    },
    props: {
        attachment: undefined,
        extendMarkerImage: {
            type: Array,
            default: function() {
                return [];
            }
        },
        extendMarkerModel: {
            type: Array,
            default: function() {
                return [];
            }
        },
        tools: {
            default: undefined
        },
        viewer: {}
    },
    components: {
        MarkerViewer,
        layerManager
    },
    mounted() {
        const self = this;
        this.$nextTick(() => {
            moveDiv("drawtoolPanel", "drawtoolHead");
            $("#drawtoolPanel .el-color-picker__icon").addClass("iconfont iconcolor");
        });
        if (this.viewer instanceof Cesium.Viewer) {
            this.init(this.viewer);
        } else if (window.viewer instanceof Cesium.Viewer) {
            this.init(window.viewer);
        }
        this.$nextTick(() => {
            self.syncColor("markerColor", self.markerColor);
            self.syncColor("lineColor", self.lineColor);
            self.syncColor("polygonColor", self.polygonColor);
        });
    },
    methods: {
        tiaoZhuan: function() {
            this.stopCreateOrEdit();
        },
        RenWuJudge: function() {
            this.stopCreateOrEdit();
            let that = this;
            if (that.layerManagerVisible) {
                that.layerManagerVisible = false;
            } else {
                that.layerManagerVisible = true;
            }
        },
        toolbarFunc: function(method) {
            switch (method) {
                case "close": {
                    this.stopCreateOrEdit();
                    if (window.showDrawManager) {
                        window.showDrawManager(false);
                    }
                    //this.$refs.layerManager.removeAll();
                    if (this.$route.name !== "EmptyComponent") {
                        this.$router.push({ name: "EmptyComponent" });
                    }
                    break;
                }

                default:
                    break;
            }
        },

        stopCreateOrEdit() {
            graphicManager && graphicManager.stopCreateOrEdit();
        },

        init(viewer) {
            checkViewer(viewer);
            if (this._viewer) {
                return;
            }
            const self = this;
            this._depthTestAgainstTerrain = viewer.scene.globe.depthTestAgainstTerrain;
            this.$refs.markerManager.init(viewer);
            this.$refs.layerManager.init();
            graphicManager = new GraphicManager(viewer);
            this.selectedModel = this.extendMarkerModel.length ? this.extendMarkerModel[0].url : undefined;
            this.cesiumViewer = viewer;
            this._viewer = viewer;
            document.addEventListener("addEvent", function(e) {
                if (graphicManager.has(e.detail.gvid) || self.$refs.markerManager.has(e.detail.gvid)) {
                    self.pushLayerManaer(e.detail.gvtype, e.detail.gvid, e.detail.gvname);
                }
            });
            document.addEventListener("stopEdit", function() {
                self.menuSelected = {};
                self.editMode = false;
                self.cesiumViewer.scene.globe.depthTestAgainstTerrain = self._depthTestAgainstTerrain;
            });
            document.addEventListener("startEdit", function(e) {
                self.menuSelected = {};
                self.menuSelected[e.detail.graphicType] = true;
                self.setControlByEvent(e);
                self.editMode = true;

                if (/.*MODEL.*/.test(self.graphicHeight)) {
                    self.cesiumViewer.scene.globe.depthTestAgainstTerrain = true;
                }
            });
            document.addEventListener("destroyEvent", function(e) {
                self.$refs.layerManager && self.$refs.layerManager.drop({ id: e.detail.gvid });
                self.cesiumViewer.scene.globe.depthTestAgainstTerrain = self._depthTestAgainstTerrain;
            });
            document.addEventListener("deleteEvent", function(e) {
                self.menuSelected = {};
                self.editMode = false;
                self.$refs.layerManager && self.$refs.layerManager.drop({ id: e.detail.gvid });
                self.cesiumViewer.scene.globe.depthTestAgainstTerrain = self._depthTestAgainstTerrain;
            });
        },
        syncColor(parent, color) {
            const parents = [parent];
            //marker和label共用同一种颜色
            if (parent === "labelColor") {
                parents.push("markerColor");
            } else if (parent === "markerColor") {
                parents.push("labelColor");
            }
            const eles = $(".el-color-picker__icon,.el-icon-arrow-down,.iconfont iconcolor");
            for (let e of eles) {
                const target = $(e)
                    .parent()
                    .parent();
                if (target.length > 0 && parents.includes(target[0].id)) {
                    $(e).css("color", color);
                }
            }
        },

        pushLayerManaer(type, id, name) {
            checkComponent(this);
            this.$refs.layerManager && this.$refs.layerManager.insertLayer(type, id, name);
        },
        modelThumb(item) {
            if (item.thumb) {
                return item.thumb;
            }
            return this.defaultImage;
        },
        getById(id) {
            checkComponent(this);
            if (graphicManager && graphicManager.has(id)) {
                return graphicManager.get(id);
            } else if (this.$refs.markerManager) {
                return this.$refs.markerManager.getById(id);
            }
        },
        selectModel(item) {
            checkComponent(this);
            this.selectedModel = item.url;
            this.modelSelectPanelvisible = false;
            this.$refs.markerManager.setModel({ uri: item.url });
        },
        /**
         * 设置当前要素的样式
         */
        setControlByEvent(e) {
            checkComponent(this);
            if (e.detail.graphicType === "POLYGON") {
                const material = e.detail.material;
                const outlineColor = e.detail.outlineColor;
                if (material) {
                    this.polygonColor = `rgba(${material.red * 255},${material.green * 255},${material.blue * 255},${material.alpha})`;
                }
                this.outline = e.detail.outline;
                if (outlineColor) {
                    this.outlineColor = `rgba(${outlineColor.red * 255},${outlineColor.green * 255},${outlineColor.blue * 255},${outlineColor.alpha})`;
                }
                this.outlineWidth = e.detail.outlineWidth;
                this.graphicHeight = e.detail.heightReference;
            } else if (e.detail.graphicType === "POLYLINE") {
                this.graphicHeight = e.detail.heightReference;
                this.lineWidth = e.detail.width;
                const plmaterial = e.detail.material;
                if (plmaterial instanceof Cesium.PolylineDashMaterialProperty) {
                    this.lineStyle = "dash";
                } else if (plmaterial instanceof Cesium.PolylineGlowMaterialProperty) {
                    this.lineStyle = "glow";
                } else if (plmaterial instanceof Cesium.PolylineArrowMaterialProperty) {
                    this.lineStyle = "arrow";
                } else {
                    this.lineStyle = "solid";
                }
                this.lineColor = `rgba(${plmaterial.getValue().color.red * 255},${plmaterial.getValue().color.green * 255},${plmaterial.getValue().color.blue * 255},${
                    plmaterial.getValue().color.alpha
                })`;
            }
        },
        stopOthers() {
            checkComponent(this);
            //   this.menuSelected = {};
            //   const manager = graphicManager.editManager;
            //   manager && manager.destroy();
            this.$refs.markerManager.stopPick();
            graphicManager.destroyManager();
            graphicManager.editManager = undefined;
        },
        setLabel() {
            checkComponent(this);
            let option;
            try {
                option = eval("(" + this.markerOption + ")");
                this.$refs.markerManager.setLabel(option);
            } catch (err) {
                console.log(err);
            }
            this.markerOptionsVisible = false;
        },
        updateMarker(gvid, gvname) {
            checkComponent(this);
            if (gvid) {
                gvname = gvname || "未命名";
                this.$refs.layerManager && this.$refs.layerManager.rename(null, gvid, gvname);
            }
            this.editMode = false;
            this.menuSelected = {};
        },
        addMarker(gvid, gvname, gvtype) {
            checkComponent(this);
            this.pushLayerManaer(gvtype, gvid, gvname);
            if (gvtype === GraphicType.MODEL) {
                this.editMode = false;
                this.menuSelected = {};
            }
        },
        closeLayerManager() {
            this.layerManagerVisible = false;
        },
        exportGraphic(type) {
            // checkComponent(this);
            // if (type === "MARKER" || type === "LABEL") {
            //     this.$refs.markerManager.export(type);
            // } else {
            //     graphicManager.export(type);
            // }
        },
        importGraphic() {
            checkComponent(this);
            document.getElementById("graphicuploadhandler").click();
        },
        importfp() {
            checkComponent(this);
            const self = this;
            const evt = event ? event : window.event;
            // const cvt = convertTool(_this.viewer)
            const files = evt.target.files,
                ext = files[0].name.split(".")[1];
            if (files.length == 0) {
                return;
            }
            const reader = new FileReader();
            if (ext.toLowerCase() === "geojson") {
                reader.readAsText(files[0]);
                reader.onload = function() {
                    // _this[_this.upload2].import(JSON.parse(this.result));
                    if (!this.result) {
                        return;
                    }
                    try {
                        const features = JSON.parse(this.result).features;
                        for (let feat of features) {
                            if (feat.geometry.type.toUpperCase() === "POINT") {
                                self.$refs.markerManager.import(feat);
                            } else {
                                graphicManager.import(feat);
                            }
                        }
                    } catch (e) {
                        console.log(e);
                    }
                    document.getElementById("graphicuploadhandler").value = "";
                };
            } else if (ext.toLowerCase() === "shp") {
                reader.readAsArrayBuffer(files[0]);
                reader.onload = function() {
                    open(this.result)
                        .then(source =>
                            source.read().then(function log(result) {
                                if (result.done) return false;
                                const feat = result.value;
                                if (feat.geometry.type === "Point") {
                                    self.$refs.markerManager.import(feat);
                                } else {
                                    graphicManager.import(feat);
                                }
                                return source.read().then(log);
                            })
                        )
                        .catch(error => console.error(error.stack));
                };
                document.getElementById("graphicuploadhandler").value = "";
            }
        },
        editMarker(type) {
            checkComponent(this);
            this.editMode = true;
            // this.stopOthers();
            if (graphicManager.editManager) {
                graphicManager.editManager.stopEdit();
                graphicManager.editManager = undefined;
            }
            this.menuSelected = {};
            this.menuSelected[type] = true;
        },
        clearGraphic() {
            this.$refs.markerManager.removeAll();
            graphicManager.removeAll();
        },
        deleteMarker(id) {
            checkComponent(this);
            this.menuSelected["MARKER"] = false;
            this.editMode = false;
            this.$refs.layerManager && this.$refs.layerManager.drop({id:id});
        },
        locateGraphic(id) {
            checkComponent(this);
            if (graphicManager.manager.has(id)) {
                const manager = graphicManager.manager.get(id);
                manager.zoomTo();
            } else {
                this.$refs.markerManager.zoomTo(id);
            }
            this.$emit("locateEvent", id);
        },
        editGraphic(id) {
            checkComponent(this);
            if (graphicManager.manager.has(id)) {
                // const manager = graphicManager.manager.get(id);
                graphicManager.edit(id);
            } else {
                this.$refs.markerManager.edit(id);
            }
            this.$emit("editEvent", id);
        },
        selectGraphic(id, state) {
            checkComponent(this);
            if (id === "marker") {
                this.$refs.markerManager.select(GraphicType.MARKER, undefined, state);
            } else if (id === "label") {
                this.$refs.markerManager.select(GraphicType.LABEL, undefined, state);
            } else if (id === "model") {
                this.$refs.markerManager.select(GraphicType.MODEL, undefined, state);
            } else if (id === "polyline") {
                graphicManager.select(GraphicType.POLYLINE, undefined, state);
            } else if (id === "label") {
                graphicManager.select(GraphicType.POLYGON, undefined, state);
            } else {
                if (graphicManager.manager.has(id)) {
                    graphicManager.select(undefined, id, state);
                } else {
                    this.$refs.markerManager.select(undefined, id, state);
                }
            }
            this.$emit("selectEvent", id, state);
        },
        deleteGraphic(id) {
            checkComponent(this);
            if (graphicManager.manager.has(id)) {
                const manager = graphicManager.manager.get(id);
                manager.destroy();
                graphicManager.manager.delete(id);
            } else {
                this.$refs.markerManager.drop(id);
            }
            this.$emit("deleteEvent", id);
            // this.$refs.layerManager.deleteNode(id)
        },
        renameGraphic(id, name) {
            checkComponent(this);
            const attr = /(.*?)</g.exec(name);
            name = /(.*?)</g.test(name) ? attr[1] : name;
            if (name === "未命名") {
                name = "";
            }
            let oname;
            if (graphicManager.has(id)) {
                oname = graphicManager.get(id).gvname;
                graphicManager.rename(id, name);
            } else {
                oname = this.$refs.markerManager.markerManager.get(id).gvname;
                this.$refs.markerManager.rename(id, name);
            }
            this.$emit("renameEvent", id, oname);
        },
        menuAction(menu) {
            this.stopCreateOrEdit();
            checkComponent(this);
            const graphic = ["MARKER", "POLYLINE", "POLYGON", "LABEL", "MODEL"];
            const bool = this.menuSelected[menu];
            this.menuSelected = {};
            graphicManager && (graphicManager.tip.visible = false);
            if (bool) {
                this.menuSelected[menu] = false;
            } else {
                this.menuSelected[menu] = true;
            }

            if (graphic.includes(menu)) {
                if (this.graphicType === menu) {
                    this.editMode = !this.editMode;
                } else {
                    this.editMode = true;
                }
                this.graphicType = menu;
            } else {
                this.editMode = false;
            }
            this.stopOthers(menu);
            if (/.*MODEL*/.test(this.graphicHeight)) {
                if (!["MARKER", "LABEL", "MODEL", "LAYER"].includes(menu))
                    //依附模型
                    //几何图形要依附于模型必须开启depthTestAgainstTerrain
                    this.cesiumViewer.scene.globe.depthTestAgainstTerrain = true;
            } else {
               // viewer.scene.globe.depthTestAgainstTerrain = this._depthTestAgainstTerrain;
            }
            switch (menu) {
                case "MARKER":
                    if (this.editMode) {
                        this.$refs.markerManager.pick("marker");
                    } else {
                        this.$refs.markerManager.cancelMark();
                    }
                    break;
                case "POLYLINE":
                    this.heightList[0].name = "空间线";
                    if (this.editMode) {
                        graphicManager.heightReference = this.graphicHeight;
                        graphicManager.material = Cesium.Color.fromCssColorString(this.lineColor);
                        graphicManager.createPolyline();
                    } else {
                        graphicManager.destroyManager();
                    }

                    break;
                case "POLYGON":
                    this.heightList[0].name = "空间面";
                    if (this.editMode) {
                        //   this.lineHeight=undefined
                        graphicManager.heightReference = this.graphicHeight;
                        const option = CesiumPolygon.defaultStyle;
                        option.outline = this.outline;
                        option.outlineColor = Cesium.Color.fromCssColorString(this.outlineColor);
                        option.outlineWidth = parseInt(this.outlineWidth);
                        // option.color = Cesium.Color.fromCssColorString(this.polygonColor);
                        graphicManager.material = Cesium.Color.fromCssColorString(this.polygonColor);
                        graphicManager.style = option;
                        graphicManager.createPolygon();
                    } else {
                        graphicManager.destroyManager();
                    }

                    break;
                case "LABEL":
                    if (this.editMode) {
                        this.$refs.markerManager.pick("label");
                    } else {
                        this.$refs.markerManager.cancelMark();
                    }
                    break;
                case "MODEL":
                    if (this.editMode) {
                        if (this.extendMarkerModel.length < 1) {
                            this.editMode = false;
                            throw new Error("没有可用的模型");
                        }
                        this.$refs.markerManager.setModel({ uri: this.selectedModel });
                        this.$refs.markerManager.pick("model");
                    } else {
                        this.$refs.markerManager.cancelMark();
                    }
            }
        },
        setLineMaterial(material, color) {
            checkComponent(this);
            switch (material) {
                case "solid":
                    graphicManager.material = color;
                    break;
                case "dash":
                    graphicManager.material = new Cesium.PolylineDashMaterialProperty({
                        color: color
                    });
                    break;
                case "glow":
                    graphicManager.material = new Cesium.PolylineGlowMaterialProperty({
                        color: color
                    });
                    break;
                case "arrow":
                    graphicManager.material = new Cesium.PolylineArrowMaterialProperty(color);
                    break;
            }
        }
    },
    watch: {
        $route: "tiaoZhuan",
        fontSize(n) {
            n = parseInt(n);
            if (isNaN(n)) {
                n = "18";
            }
            n = n + "px";
            // console.log(this.$refs.markerManager.getFont())
            const fontFamily = this.menuSelected["MARKER"] ? this.markerFont : this.fontFamily;

            this.$refs.markerManager.setFont(n + " " + fontFamily);
        },
        markerColor(n) {
            if (!n) {
                return;
            }
            this.$refs.markerManager.setColor(Cesium.Color.fromCssColorString(n));
            this.syncColor("markerColor", n);
        },
        graphicHeight(n) {
            if (n === undefined) {
                return;
            }
            graphicManager.heightReference = n;
        },
        lineColor(n) {
            if (!n) {
                return;
            }
            const color = Cesium.Color.fromCssColorString(n);
            const matrial = graphicManager.editManager.material;
            let materialStyle = "solid";
            if (matrial instanceof Cesium.PolylineDashMaterialProperty) {
                materialStyle = "dash";
            } else if (matrial instanceof Cesium.PolylineGlowMaterialProperty) {
                materialStyle = "glow";
            } else if (matrial instanceof Cesium.PolylineArrowMaterialProperty) {
                materialStyle = "arrow";
            }
            //   matrial.color = Cesium.clone(color);
            this.setLineMaterial(materialStyle, color);
            this.syncColor("lineColor", n);
        },
        lineStyle(n) {
            if (!this.lineColor) {
                return;
            }
            const color = Cesium.Color.fromCssColorString(this.lineColor);
            this.setLineMaterial(n, color);
        },
        lineWidth(n) {
            let width = parseInt(n);
            if (isNaN(width)) {
                width = 3;
            }
            graphicManager.style = { width: width };
        },
        outline(n) {
            if (n) {
                graphicManager.editManager.createOutline();
                const color = Cesium.Color.fromCssColorString(this.outlineColor);
                const width = parseInt(this.outlineWidth) || 3;
                graphicManager.editManager.outline = n;
                graphicManager.style = {
                    outline: true,
                    outlineWidth: width,
                    outlineColor: color
                };
            } else {
                graphicManager.editManager.removeOutline();
            }
        },
        polygonColor(n) {
            if (!n) {
                return;
            }
            const color = Cesium.Color.fromCssColorString(n);
            graphicManager.material = color;
            this.syncColor("polygonColor", n);
        },
        outlineColor(n) {
            if (!n) {
                return;
            }
            const color = Cesium.Color.fromCssColorString(n);
            graphicManager.style = { outlineColor: color };
            this.syncColor("outlineColor", n);
        },
        outlineWidth(n) {
            const width = parseInt(n) || 3;
            graphicManager.style = { outlineWidth: width };
        },
        fontFamily(n) {
            let size = parseInt(this.fontSize);
            if (isNaN(size)) {
                size = "18";
            }
            size = size + "px";
            // console.log(this.$refs.markerManager.getFont())

            this.$refs.markerManager.setFont(size + " " + n);
        },
        modelColor(n) {
            if (!n) {
                return;
            }
            const color = Cesium.Color.fromCssColorString(n);
            this.$refs.markerManager.setModel({ color: color });
            this.syncColor("modelColor", n);
        },
        modelMode(n) {
            const mode = Cesium.ColorBlendMode[n.toUpperCase()];
            this.$refs.markerManager.setModel({ mode: mode });
        },
        modelMixed(n) {
            this.$refs.markerManager.setModel({ mixed: n });
        }
    },
    beforeDestroy() {
        this.stopCreateOrEdit();
    },
    destroyed() {
        graphicManager = undefined;
    }
};
</script>

<style scoped>
.el-container {
    color: #ffffff;
}

.el-header {
    line-height: 60px;
}

.el-main {
    margin: 3px 3px 0 3px;
    padding: 3px;
}
</style>
